package org.lionsoul.websnail.store;

import redis.clients.jedis.Jedis;

/**
 * Persistent todo list base on redis
 *
 * @author yangjian
 **/
public class RedisTodo implements Todo
{

    private final Jedis jedis;
    private final String key;

    /**
     * @param host     redis server host
     * @param port     redis server port
     * @param database redis database index
     * @param key      key for list in redis
     */
    public RedisTodo(String host, int port, int database, String key)
    {
        jedis = new Jedis(host, port);
        if (database > 0) { // 指定数据库
            jedis.select(database);
        }
        this.key = key;
    }

    @Override
    public synchronized boolean add(String url)
    {
        jedis.rpush(key, url);
        return true;
    }

    @Override
    public synchronized boolean add(String[] urls)
    {
        for (String url : urls) {
            add(url);
        }
        return true;
    }

    @Override
    public synchronized boolean addFirst(String url)
    {
        jedis.lpush(key, url);
        return true;
    }

    @Override
    public synchronized boolean addFirst(String[] urls)
    {
        for (String url : urls) {
            addFirst(url);
        }
        return true;
    }

    @Override
    public synchronized void clear()
    {
        jedis.del(key);
    }

    @Override
    public synchronized String shift()
    {
        return jedis.lpop(key);
    }

    @Override
    public synchronized String pop()
    {
        return jedis.rpop(key);
    }

    @Override
    public synchronized int size()
    {
        return (int) jedis.llen(key);
    }

    @Override
    public synchronized void close()
    {
        jedis.close();
    }
}
